package study.week05.question01;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.concurrent.ConcurrentHashMap;

public class AopDemo {
    public static void main(String[] args) {
        //创建并初始化上下文
        Context ctx = new Context();
        ctx.init();
        //从上下文里获取bean并执行
        IStudent student = (IStudent) ctx.getBean(IStudent.class);
        student.study();
    }

}

/**
 * 上下文
 */
class Context {

    private  ConcurrentHashMap<Class<?>,Object> context = new ConcurrentHashMap<>();

    public Object getBean(Class<?> key){
      return   context.get(key);
    }

    public void init() {
        //在上下文中创建一个student类型的bean
        IStudent student = new Student();
        CustomHandlerImpl handler = new CustomHandlerImpl(student);
        ClassLoader loader = student.getClass().getClassLoader();
        student = (IStudent) Proxy.newProxyInstance(loader, new Class[]{IStudent.class}, handler);
        context.put(IStudent.class,student);

    }

}

/**
 * 代理的handler
 */
class CustomHandlerImpl implements InvocationHandler
{
    /**
     * 代理的真实对象
     */
    private Object target;
    public CustomHandlerImpl(Object target)
    {
        this.target = target;
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
    {
        System.out.println("aop before...");
        Object returnValue = method.invoke(target, args);
        System.out.println("aop after...");
        return returnValue;
    }
}

/**
 * 学生接口
 */
interface IStudent{
    void study();
}

/**
 * 学生实现类
 */
class Student implements IStudent{

    @Override
    public void study() {
        System.out.println("student study()");
    }
}